package com.CmJava.Dubbo.provider.httpServer.handler;

import com.CmJava.Dubbo.consumer.httpClient.parameters.Invocation;
import com.CmJava.Dubbo.provider.register.localRegister.LocalRegister;
import org.apache.commons.io.IOUtils;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

public class HttpServerHandler  {
    public void handler(HttpServletRequest request, HttpServletResponse response){
        InputStream inputStream=null;
        ObjectInputStream objectInputStream=null;
        try {
            inputStream = request.getInputStream();
            objectInputStream = new ObjectInputStream(inputStream);
            Invocation invocation = (Invocation) objectInputStream.readObject();

            if (invocation!=null) {
                String interfaceName = invocation.getInterfaceName();
                String methodName = invocation.getMethodName();
                Class[] parametersClass = invocation.getParametersClass();
                Object[] parameters = invocation.getParameters();

                //获取接口实现类
                Class anInterface = LocalRegister.getInterface(interfaceName);
                if (anInterface!=null){
                    Method method = anInterface.getMethod(methodName, parametersClass);
                    if (method!=null){
                        String result = (String) method.invoke(anInterface.newInstance(), parameters);
                        ServletOutputStream outputStream = response.getOutputStream();
                        IOUtils.write(result, outputStream);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
